Session 2 Cheat Sheet — R and RStudio Basics
Applied Methods · MA Public Administration
1. Useful dplyr verbs at a glance
| Task | Function | Example |
|---|---|---|
| Create/change variables | mutate() |
mutate(rate = x / pop) |
| Keep rows | filter() |
filter(year == 2020) |
| Keep columns | select() |
select(Mun, year, pop) |
| Reorder rows | arrange() |
arrange(desc(pop)) |
| Rename variables | rename() |
rename(population = pop) |
| Group observations | group_by() |
group_by(Mun) |
| Remove grouping | ungroup() |
ungroup() |
| Collapse to summaries | summarise() |
summarise(mean = mean(pop)) |
| Count observations | count() |
count(year) |
| Extract rows by position | slice() |
slice(1:10) |
| Largest values | slice_max() |
slice_max(pop, n = 5) |
| Smallest values | slice_min() |
slice_min(pop, n = 5) |
| Apply to many variables | across() |
across(starts_with("X"), as.numeric) |
| Join datasets | left_join() |
left_join(data2, by = "id") |
2. Useful base R functions at a glance
| Task | Function |
|---|---|
| Number of rows | nrow() |
| Number of columns | ncol() |
| Dimensions | dim() |
| Variable names | names() |
| First observations | head() |
| Last observations | tail() |
| Structure | str() |
| Summary | summary() |
| Class | class() |
| Unique values | unique() |
| Length | length() |
| Frequency table | table() |
| Mean | mean() |
| Median | median() |
| Standard deviation | sd() |
| Variance | var() |
| Minimum | min() |
| Maximum | max() |
| Quantiles | quantile() |
| Missing values | is.na() |
| String replacement | gsub() |
| String substring | substr() |
| Repetition | rep() |
| Apply function to list/columns | lapply() |
| Merge datasets | merge() |
| Position of maximum | which.max() |
3. Command map
Import data
read.csv()
read.csv2()
read_xlsx()Inspect data
head()
tail()
View()
summary()
str()
glimpse()
names()
nrow()
ncol()
dim()Check variable types
class()
typeof()
is.numeric()
is.character()
is.factor()Convert variables
as.numeric()
as.character()
as.integer()
as.factor()
as.Date()Clean strings
gsub()
sub()
substr()
grepl()Create variables
mutate()
ifelse()
case_when()
recode()Select variables
select()
starts_with()
ends_with()
contains()
matches()Rename and reorder variables
rename()
relocate()Keep observations
filter()Sort observations
arrange()
desc()Select rows
slice()
slice_head()
slice_tail()
slice_max()
slice_min()Count observations
table()
count()
n()
n_distinct()Apply functions to many variables
across()
lapply()Row-wise calculations
rowSums()
rowMeans()
rowwise()
c_across()Merge datasets
merge()
inner_join()
left_join()
right_join()
full_join()
anti_join()
semi_join()Reshape data
pivot_longer()
pivot_wider()Grouped operations
group_by()
mutate()
summarise()
ungroup()Descriptive statistics
mean()
median()
sd()
var()
min()
max()
range()
quantile()
IQR()Missing values
is.na()Time or ordered data
lag()
lead()Check data structure
unique()
n_distinct()
count()
complete()4. Reusable templates
Create a variable
data <- data %>%
mutate(
new_variable =
expression
)Recode a binary variable
data <- data %>%
mutate(
new_variable =
ifelse(
condition,
1,
0
)
)Recode multiple categories
data <- data %>%
mutate(
category =
case_when(
condition1 ~ "A",
condition2 ~ "B",
condition3 ~ "C",
TRUE ~ NA_character_
)
)Filter observations
data_filtered <- data %>%
filter(
condition
)Select variables
data_selected <- data %>%
select(
id,
x,
y
)Sort observations
data_sorted <- data %>%
arrange(
desc(x)
)Apply a function to several variables
data <- data %>%
mutate(
across(
x1:x5,
function_name
)
)Grouped variable
data <- data %>%
group_by(group) %>%
mutate(
group_mean =
mean(
x,
na.rm = TRUE
)
) %>%
ungroup()Grouped summary
summary_data <- data %>%
group_by(group) %>%
summarise(
n = n(),
mean_x =
mean(
x,
na.rm = TRUE
),
sd_x =
sd(
x,
na.rm = TRUE
),
.groups = "drop"
)Long format
data_long <- data %>%
pivot_longer(
cols = x1:x5,
names_to = "variable",
values_to = "value"
)Wide format
data_wide <- data %>%
pivot_wider(
names_from = variable,
values_from = value
)Join two datasets
data_merged <- data1 %>%
left_join(
data2,
by = "id"
)Find largest values
data %>%
slice_max(
x,
n = 5
)5. Final rule of thumb
When working with R, first identify the type of operation you need.
If you want to…
- create or transform a variable →
mutate() - keep observations →
filter() - keep variables →
select() - sort observations →
arrange() - combine datasets →
*_join() - change data shape →
pivot_longer()/pivot_wider() - calculate by groups →
group_by() - keep rows while calculating group statistics →
mutate() - collapse rows into group statistics →
summarise() - apply the same transformation to many variables →
across()
The important skill is not memorizing all syntax. It is learning to recognize which operation matches the problem you are trying to solve.